package com.ruoyi.toobit.controller;

import com.ruoyi.toobit.service.TooBitApiService;
import com.ruoyi.toobit.task.TooBitApiScheduledTask;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;

/**
 * TooBit API定时任务管理控制器
 * 
 * @author TooBit
 * @date 2025-01-06
 */
@RestController
@RequestMapping("/toobit/scheduled")
public class TooBitScheduledTaskController extends BaseController {
    
    private static final Logger log = LoggerFactory.getLogger(TooBitScheduledTaskController.class);
    
    @Autowired
    private TooBitApiScheduledTask scheduledTask;
    
    @Autowired
    private TooBitApiService tooBitApiService;
    
    /**
     * 获取定时任务统计信息
     */
    @GetMapping("/statistics")
    public AjaxResult getTaskStatistics() {
        log.info("📊 获取TooBit API定时任务统计信息");
        
        try {
            Map<String, Object> statistics = scheduledTask.getTaskStatistics();
            statistics.put("currentTime", LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
            statistics.put("taskType", "TooBit API ExchangeInfo");
            statistics.put("schedule", "每分钟执行一次");
            
            return AjaxResult.success("定时任务统计信息获取成功", statistics);
            
        } catch (Exception e) {
            log.error("🚨 获取定时任务统计失败: {}", e.getMessage(), e);
            return AjaxResult.error("获取统计信息失败: " + e.getMessage());
        }
    }
    
    /**
     * 手动执行一次API请求测试
     */
    @PostMapping("/execute/test")
    public AjaxResult executeTestRequest() {
        log.info("🧪 手动执行TooBit API测试请求");
        
        try {
            long startTime = System.currentTimeMillis();
            String response = tooBitApiService.getExchangeInfoWithSignature();
            long endTime = System.currentTimeMillis();
            
            Map<String, Object> result = new HashMap<>();
            result.put("executionTime", LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
            result.put("responseTime", endTime - startTime);
            result.put("success", response != null && !response.isEmpty());
            
            if (response != null && !response.isEmpty()) {
                result.put("symbolCount", countOccurrences(response, "\"symbol\":"));
                result.put("dataLength", response.length());
                result.put("status", "SUCCESS");
                
                // 检查关键交易对
                String[] keyPairs = {"BTCUSDT", "ETHUSDT", "DOGEUSDT", "TRXUSDT"};
                Map<String, Boolean> keyPairStatus = new HashMap<>();
                for (String pair : keyPairs) {
                    keyPairStatus.put(pair, response.contains("\"" + pair + "\""));
                }
                result.put("keyTradingPairs", keyPairStatus);
                
                return AjaxResult.success("手动测试执行成功", result);
            } else {
                result.put("status", "FAILED");
                result.put("error", "API响应为空");
                return AjaxResult.error("手动测试执行失败", result);
            }
            
        } catch (Exception e) {
            log.error("🚨 手动测试执行异常: {}", e.getMessage(), e);
            return AjaxResult.error("手动测试执行异常: " + e.getMessage());
        }
    }
    
    /**
     * 执行完整验签测试
     */
    @PostMapping("/execute/fullSignature")
    public AjaxResult executeFullSignatureTest() {
        log.info("🔐 手动执行TooBit API完整验签测试");
        
        try {
            long startTime = System.currentTimeMillis();
            String response = tooBitApiService.getExchangeInfoWithFullSignature();
            long endTime = System.currentTimeMillis();
            
            Map<String, Object> result = new HashMap<>();
            result.put("executionTime", LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
            result.put("responseTime", endTime - startTime);
            result.put("success", response != null && !response.isEmpty());
            result.put("signatureType", "HMAC SHA256");
            result.put("authType", "USER_DATA");
            
            if (response != null && !response.isEmpty()) {
                result.put("symbolCount", countOccurrences(response, "\"symbol\":"));
                result.put("dataLength", response.length());
                result.put("status", "SUCCESS");
                result.put("signatureVerified", true);
                
                return AjaxResult.success("完整验签测试执行成功", result);
            } else {
                result.put("status", "FAILED");
                result.put("signatureVerified", false);
                result.put("error", "API响应为空");
                return AjaxResult.error("完整验签测试执行失败", result);
            }
            
        } catch (Exception e) {
            log.error("🚨 完整验签测试异常: {}", e.getMessage(), e);
            return AjaxResult.error("完整验签测试异常: " + e.getMessage());
        }
    }
    
    /**
     * 获取API连接健康状态
     */
    @GetMapping("/health")
    public AjaxResult getApiHealth() {
        log.info("🏥 检查TooBit API连接健康状态");
        
        try {
            Map<String, Object> healthStatus = tooBitApiService.validateApiConnection();
            healthStatus.put("checkTime", LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
            
            String status = (String) healthStatus.get("status");
            if ("connected".equals(status)) {
                return AjaxResult.success("API连接正常", healthStatus);
            } else {
                return AjaxResult.error("API连接异常", healthStatus);
            }
            
        } catch (Exception e) {
            log.error("🚨 API健康检查异常: {}", e.getMessage(), e);
            return AjaxResult.error("健康检查异常: " + e.getMessage());
        }
    }
    
    /**
     * 获取定时任务配置信息
     */
    @GetMapping("/config")
    public AjaxResult getTaskConfig() {
        log.info("⚙️ 获取定时任务配置信息");
        
        try {
            Map<String, Object> config = new HashMap<>();
            config.put("taskName", "TooBit API ExchangeInfo 定时任务");
            config.put("schedule", "每分钟执行一次 (cron: 0 * * * * ?)");
            config.put("fullSignatureSchedule", "每5分钟执行一次 (cron: 0 */5 * * * ?)");
            config.put("healthCheckSchedule", "每30分钟执行一次 (cron: 0 */30 * * * ?)");
            config.put("apiEndpoint", "https://api.toobit.com/api/v1/exchangeInfo");
            config.put("authType", "MARKET_DATA (API Key)");
            config.put("fullSignatureAuthType", "USER_DATA (HMAC SHA256)");
            config.put("enabled", true);
            config.put("description", "定时获取TooBit交易所交易对信息，验证API连接状态");
            
            return AjaxResult.success("定时任务配置获取成功", config);
            
        } catch (Exception e) {
            log.error("🚨 获取任务配置异常: {}", e.getMessage(), e);
            return AjaxResult.error("获取配置失败: " + e.getMessage());
        }
    }
    
    /**
     * 获取最近的API响应示例
     */
    @GetMapping("/sample")
    public AjaxResult getApiResponseSample() {
        log.info("📄 获取API响应示例数据");
        
        try {
            String response = tooBitApiService.getExchangeInfoWithSignature();
            
            if (response != null && !response.isEmpty()) {
                Map<String, Object> sample = new HashMap<>();
                sample.put("sampleTime", LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
                sample.put("totalLength", response.length());
                sample.put("symbolCount", countOccurrences(response, "\"symbol\":"));
                
                // 提供响应数据的前1000个字符作为示例
                if (response.length() > 1000) {
                    sample.put("preview", response.substring(0, 1000) + "...");
                } else {
                    sample.put("fullResponse", response);
                }
                
                // 提取服务器时间
                int serverTimeIndex = response.indexOf("\"serverTime\":\"");
                if (serverTimeIndex != -1) {
                    int startIndex = serverTimeIndex + 14;
                    int endIndex = response.indexOf("\"", startIndex);
                    if (endIndex != -1) {
                        sample.put("serverTime", response.substring(startIndex, endIndex));
                    }
                }
                
                return AjaxResult.success("API响应示例获取成功", sample);
            } else {
                return AjaxResult.error("无法获取API响应示例");
            }
            
        } catch (Exception e) {
            log.error("🚨 获取API响应示例异常: {}", e.getMessage(), e);
            return AjaxResult.error("获取示例失败: " + e.getMessage());
        }
    }
    
    /**
     * 计算字符串中指定子串的出现次数
     */
    private int countOccurrences(String text, String pattern) {
        if (text == null || pattern == null) {
            return 0;
        }
        
        int count = 0;
        int index = 0;
        while ((index = text.indexOf(pattern, index)) != -1) {
            count++;
            index += pattern.length();
        }
        return count;
    }
}